const OSS = require('ali-oss')
const path = require('path')

/**
 * 初始化客户端
 */
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
})

/**
 * 上传文件
 * @param {*} file
 * @returns
 */
const uploadFile = async (file) => {
  try {
    // 1. 生成唯一的文件名，避免冲突
    const extension = path.extname(file.originalname)
    const timestamp = Date.now()
    const randomString = Math.random().toString(36).substring(2, 8)
    const fileName = `uploads/${timestamp}-${randomString}${extension}`

    // 2. 调用 OSS SDK 的 put 方法上传文件
    const result = await client.put(fileName, file.buffer)

    // 3. 上传成功，返回文件在 OSS 中的地址和名称
    return {
      url: result.url,
      filename: result.name,
    }
  } catch (error) {
    console.error('OSS上传失败:', error)
    throw error
  }
}

module.exports = {
  uploadFile,
}
